# encoding: utf-8
class Admin::TerminalOrdersController < AdminController

  set_tab :terminals

  respond_to :html, :json

  def index
    params[:order] ||= {}
    @orders = TerminalOrder
    @orders = @orders.where(terminal_group_id: params[:order][:terminal_group_id]) unless params[:order][:terminal_group_id].blank?
    @orders = @orders.order('created_at desc').page params[:page]
  end

  def new
    @order = TerminalOrder.new(terminal_group_id: params[:terminal_group_id])
    @order.build_terminal(terminal_group_id: params[:terminal_group_id])
    @order.build_terminal_user   
  end

  def edit
    @order = TerminalOrder.find params[:id]
  end

  def create
    @order = TerminalOrder.new(params[:terminal_order])
    render :action => :new unless @order.save
  end

  def update
    @order = TerminalOrder.find params[:id]
    render :action => :edit unless @order.update_attributes(params[:terminal_order])
  end

  def export
    respond_to do |format|
      format.csv {   
        send_data TerminalOrder.to_csv,:type => "text/csv;charset=utf-8; header=present",  
          :filename => "工单模板_#{Time.now.strftime("%Y%m%d")}.csv"
      }
    end
  end

  def import
    begin
      TerminalOrder.import(params[:file],params[:terminal_group_id])
      @success = "工单导入成功."
    rescue => e
      @error = e
    end
    redirect_to admin_terminals_url(terminal_group_id: params[:terminal_group_id]), :flash => { error: @error.to_s, success: @success }
  end

end
